package com.xiaoma.myaudience.biz.activity;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.Html;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.widget.Button;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RatingBar;
import android.widget.ScrollView;
import android.widget.TextView;

import com.xiaoma.myaudience.R;
import com.xiaoma.myaudience.biz.adapter.ActivitysDetailAdapter;
import com.xiaoma.myaudience.biz.model.ActivityDetailInfoModel;
import com.xiaoma.myaudience.biz.model.RankingListModel;
import com.xiaoma.myaudience.biz.task.ActivitysDetailTask;
import com.xiaoma.myaudience.biz.task.ActivitysQuitTask;
import com.xiaoma.myaudience.biz.task.AddEventTask;
import com.xiaoma.myaudience.biz.task.DataAsyncTask;
import com.xiaoma.myaudience.biz.util.Constant;
import com.xiaoma.myaudience.biz.view.HorizontalListView;
import com.xiaoma.myaudience.biz.view.LoadingImageView;
import com.xiaoma.myaudience.util.PicUtils;
import com.xiaoma.myaudience.util.PrefHelper;
import com.xiaoma.myaudience.util.activity.BaseActivity;
import com.xiaoma.myaudience.util.model.ModelUtils;

/**
 * 活动详细页面
 * @author jpren
 *
 */
public class ActivitysDetailActivity extends BaseActivity  implements OnClickListener{
	private static final String TAG = "ActivitysDetailActivity";
	private static final int DIALOG_ADD_EVENT = 0;
	private static final int DIALOG_ADD_EVENT_ERROR = 1;
	private static final int DIALOG_ADD_EVENT_NO_LOGIN = 2;
	private static final int DIALOG_ADD_EVENT_NEED_FULL = 3;
	private String mSizeStr;
	public String mEventId;
	private String mErrorMsg;
	private boolean mInfoClicked;
	private HorizontalListView mListView;
	
	private ActivitysDetailTask mActivitysDetailTask;
	private ActivitysQuitTask mActivitysQuitTask;
	private AddEventTask mAddEventTask;
	private ScrollView mContentLayout;
	private String mStatus;
	private Map<String, Object> mObjMap;
	private Button mBtnattend;
	private Boolean isNeedChecked = false;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.activitys_detail_layout);
		
		setNetEaseTitleBarVisibility(View.VISIBLE);
        setNetEaseTitleGravity(Gravity.CENTER);
        setNetEaseTitleBarExtra(R.layout.video_detail_extra_layout);
        mSizeStr = PicUtils.composeSize((int) this.getResources().getDimension(
                R.dimen.list_item_img_width), (int) this.getResources().getDimension(
                R.dimen.list_item_img_height));
        
        findViewById(R.id.btn_back).setOnClickListener(this);
        findViewById(R.id.review).setOnClickListener(this);
        findViewById(R.id.activity_tip).setOnClickListener(this);
        findViewById(R.id.activity_detail).setOnClickListener(this);
        mContentLayout = (ScrollView) findViewById(R.id.activity_detail_con);
        mBtnattend = (Button)findViewById(R.id.play);
        mListView = (HorizontalListView) findViewById(R.id.listview); 
        
        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
			mEventId = bundle.getString(ActivityDetailInfoModel.PARAM_EVENTID);
		}
        execute();
        
      //TODO:参加活动
       findViewById(R.id.play).setOnClickListener(new OnClickListener() {
			@Override 
			public void onClick(View v) {
				int status = Integer.valueOf(mStatus);
				Boolean islogin = PrefHelper.getBoolean(ActivitysDetailActivity.this, Constant.LOGIN_ISLOGIN, false);
				switch (status) {
				case 0:
					if (islogin) {
						//已登录都给丫显示
						showAddInfoDialog(R.string.add_event_txt);
						return;
					} else {
						showDialog(DIALOG_ADD_EVENT_NO_LOGIN);
					}
					break;
				case 3:
				case 4:
					if (islogin) {
						executeQuit();
					} else {
						showDialog(DIALOG_ADD_EVENT_NO_LOGIN);
					}
					break;

				default:
					break;
				}
			}
       });
	}
	
	private void execute() {
		cancel();
		mActivitysDetailTask = new ActivitysDetailTask(this, DataAsyncTask.TASK_ACTIVITYS_DETAIL, this);
		Map<String,String> cookie = new HashMap<String,String>();
		cookie.put(Constant.LOGIN_COOKIE1,PrefHelper.getString(ActivitysDetailActivity.this,Constant.LOGIN_COOKIE1,""));
		cookie.put(Constant.LOGIN_COOKIE2,PrefHelper.getString(ActivitysDetailActivity.this,Constant.LOGIN_COOKIE2,""));
		cookie.put("url", mEventId);
		mActivitysDetailTask.execute(cookie);
	}
	
	private void executeQuit() {
		cancelQuit();
		mActivitysQuitTask = new ActivitysQuitTask(this, DataAsyncTask.TASK_QUIT_EVENT, this);
		Map<String,String> cookie = new HashMap<String,String>();
		cookie.put(Constant.LOGIN_COOKIE1,PrefHelper.getString(ActivitysDetailActivity.this,Constant.LOGIN_COOKIE1,""));
		cookie.put(Constant.LOGIN_COOKIE2,PrefHelper.getString(ActivitysDetailActivity.this,Constant.LOGIN_COOKIE2,""));
		cookie.put("url", mEventId);
		mActivitysQuitTask.execute(cookie);
	}
	
	private void cancelQuit() {
		if (mActivitysQuitTask != null) {
			mActivitysQuitTask.cancel(true, true);
		}
		mActivitysQuitTask = null;
	}
	
	private void cancel() {
		if (mActivitysDetailTask != null) {
			mActivitysDetailTask.cancel(true, true);
		}
		mActivitysDetailTask = null;
	}
	
	private void addEvent() {
		if (mAddEventTask != null) {
			mAddEventTask.cancel(true, true);
		}
		mAddEventTask = null;
		
		mAddEventTask = new AddEventTask(this, DataAsyncTask.TASK_ADD_EVENT, this);
		Map<String,String> cookie = new HashMap<String,String>();
		cookie.put(Constant.LOGIN_COOKIE1,PrefHelper.getString(ActivitysDetailActivity.this,Constant.LOGIN_COOKIE1,""));
		cookie.put(Constant.LOGIN_COOKIE2,PrefHelper.getString(ActivitysDetailActivity.this,Constant.LOGIN_COOKIE2,""));
		cookie.put("url", mEventId);
		mAddEventTask.execute(cookie);
	}
	
	private void initData(Map<String, Object> map) {
		Map<String, Object> eventMap = null;
		if (map != null) {
			eventMap = ModelUtils.getMapValue(map, ActivityDetailInfoModel.PARAM_EVENT);
		}
		if (eventMap != null) {
			((LoadingImageView) findViewById(R.id.img)).setLoadingDrawable(
					ModelUtils.getStringValue(eventMap, ActivityDetailInfoModel.PARAM_POSTER), 
					mSizeStr);
			String score = ModelUtils.getStringValue(eventMap, ActivityDetailInfoModel.PARAM_STARLEVEL);
			((TextView)findViewById(R.id.score)).setText(score);
			Double d = Math.ceil(Double.valueOf(score)/2.0);
			((RatingBar)findViewById(R.id.rating_bar)).setRating(Float.valueOf(score) == null ? 0.0f :  Float.valueOf(d.toString()));
			String title = ModelUtils.getStringValue(eventMap, ActivityDetailInfoModel.PARAM_TITLE);
			if (!TextUtils.isEmpty(title)) {
				if(title.trim().length()>5){
					setNetEaseTitle(title.subSequence(0, 5) + "...");
				}else{
					setNetEaseTitle(title);
				}
			}
			((TextView)findViewById(R.id.title)).setText(title);
			((TextView)findViewById(R.id.zcr)).setText("主持人：" + ModelUtils.getStringValue(eventMap, RankingListModel.PARAM_ZCR));
			((TextView)findViewById(R.id.type)).setText("活动类型：" + ModelUtils.getStringValue(eventMap, RankingListModel.PARAM_CLASSNAME));
			((TextView)findViewById(R.id.jb)).setText("活动嘉宾：" + ModelUtils.getStringValue(eventMap, RankingListModel.PARAM_JB));
			((TextView)findViewById(R.id.location)).setText("活动地点：" + ModelUtils.getStringValue(eventMap, RankingListModel.PARAM_LOCATION));
			((TextView)findViewById(R.id.start_time)).setText("开始时间：" + ModelUtils.getStringValue(eventMap, RankingListModel.PARAM_STARTTIME));
			((TextView)findViewById(R.id.dateline_time)).setText("截止报名：" + ModelUtils.getStringValue(eventMap, RankingListModel.PARAM_DEADTIME));
			((TextView)findViewById(R.id.limit_num)).setText("活动人数：" + ModelUtils.getStringValue(eventMap, RankingListModel.PARAM_LIMITNUM));
			isNeedChecked = "1".equals(ModelUtils.getStringValue(eventMap, RankingListModel.PARAM_VERIFY)) ;
			((TextView)findViewById(R.id.verify)).setText("需要审核：" + (isNeedChecked? "需要" : "不需要"));
			
			String jifen =  ModelUtils.getStringValue(eventMap, RankingListModel.PARAM_JIFENG) ;
			int sjififen = Integer.valueOf(jifen);
			String jfString = (sjififen < 0 ? "参加活动：需要花费 " + (-sjififen) : "参加活动：奖励" + sjififen) + "能量/人";
			((TextView)findViewById(R.id.jifeng)).setText(jfString);
			((TextView)findViewById(R.id.all_time)).setText(String.format("%s次查看 | %s人参加 | %s待审核", ModelUtils.getStringValue(eventMap, RankingListModel.PARAM_VIEWNUM) ,
					ModelUtils.getStringValue(eventMap, RankingListModel.PARAM_MEMBERNUM), 
					ModelUtils.getStringValue(eventMap, RankingListModel.PARAM_SHENHE)));
			mStatus = ModelUtils.getStringValue(eventMap, ActivityDetailInfoModel.PARAM_STATUS);
			getStatus(Integer.valueOf(mStatus), ((Button)findViewById(R.id.play)));
			((TextView)findViewById(R.id.activity_detail_content)).setText(Html.fromHtml(ModelUtils.getStringValue(eventMap, ActivityDetailInfoModel.PARAM_DETAIL)));
			final String x = ModelUtils.getStringValue(map, RankingListModel.PARAM_LOCATION_X);
			final String y = ModelUtils.getStringValue(map, RankingListModel.PARAM_LOCATION_Y);
			TextView locView = (TextView)findViewById(R.id.location);
			if(x.equals("") || y.equals("") || null==x|| null==y){
				locView.setCompoundDrawablesWithIntrinsicBounds(null, null, getResources().getDrawable(R.drawable.review_location_icon), null);
			}else{
				locView.setOnClickListener(new OnClickListener() {
					
					@Override
					public void onClick(View v) {
						Intent intent = new Intent(ActivitysDetailActivity.this, LocationMapActivity.class);
						intent.putExtra(ActivityDetailInfoModel.PARAM_LOCATION_X, x);
						intent.putExtra(ActivityDetailInfoModel.PARAM_LOCATION_Y, y); 
						ActivitysDetailActivity.this.startActivity(intent);
					}
				});
			}
			List<Map<String, Object>> list = ModelUtils.getListMapValue(map, ActivityDetailInfoModel.PARAM_EVENTPICS);
			if (list != null) {
				ActivitysDetailAdapter adapter = new ActivitysDetailAdapter(this, list,mEventId);
				mListView.setAdapter(adapter);
			}
			
			
			
			findViewById(R.id.review).setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					Intent intent = new Intent(ActivitysDetailActivity.this, ReviewActivity.class);
					intent.putExtra("eventid", mEventId);
					intent.putExtra("type", "1");
					ActivitysDetailActivity.this.startActivity(intent);
				}
			});
		}
	}
	
	private void getStatus(int status, Button btn) {
		String name = "参加活动";
		switch (status) {
		case 0:
			name = "参加活动";
			btn.setBackgroundResource(R.drawable.add_event_selector);
			mListView.setVisibility(View.GONE);

			break;
		case 1:
			name = "报名已截止";
			btn.setEnabled(false);
			break;
		case 2:
			name = "活动已结束";
			btn.setEnabled(false);
			mContentLayout.setVisibility(View.GONE);
			break;
		case 3:
			name = "退出活动（待审核）";
			btn.setBackgroundResource(R.drawable.add_event_selector);
			mListView.setVisibility(View.GONE);
			break;
		case 4:
			name = "退出活动（已审核）";
			if(isNeedChecked) name = "退出活动（待审核）";
			btn.setBackgroundResource(R.drawable.add_event_selector);
			mListView.setVisibility(View.GONE);
			break;

		default:
			break;
		}
		
		btn.setText(name);
	}
	
	private void addEventPorcess(Map<String, Object> map) {
		if (!"0".equals(ModelUtils.getStringValue(map, "code"))) {
			mErrorMsg = ModelUtils.getStringValue(map, "errorMsg");
			showDialog(DIALOG_ADD_EVENT_ERROR);
			//dismissDialog(DIALOG_ADD_EVENT_ERROR);
		} else {
			//弹出信息
			Map<String, Object> data = ModelUtils.getMapValue(map, "data");
			String nengLiang = ModelUtils.getStringValue(data, "nengliang");
			int i = Integer.valueOf(nengLiang);
			mErrorMsg = (i > 0 ? "参加成功，奖励" + Math.abs(i) : "参加成功，消耗" + Math.abs(i)) + "能量";
			boolean verify = ModelUtils.getStringValue(mObjMap, RankingListModel.PARAM_VERIFY) == "1" ? true : false;
			ModelUtils.getMapValue(mObjMap, ActivityDetailInfoModel.PARAM_EVENT).put(RankingListModel.PARAM_STATUS, verify ? "3" : "4");
			String s = isNeedChecked?"退出活动（待审核）":"退出活动（已审核）";
			mBtnattend.setText(s);
			mBtnattend.setBackgroundResource(R.drawable.add_event_selector);
			removeDialog(DIALOG_ADD_EVENT_ERROR);
			showDialog(DIALOG_ADD_EVENT_ERROR);
		}
	}
	
	private void showAddInfoDialog(final int string) {
		final AlertDialog dlg = new AlertDialog.Builder(this).create();
		 dlg.show();
		 Window window = dlg.getWindow();
		 window.setContentView(R.layout.add_event_view_layout);
		 if (string == R.string.add_event_txt) {
			 ((TextView)window.findViewById(R.id.base_title_bar_title)).setText(R.string.add_event_title_xy);
		 }else {
			((TextView)window.findViewById(R.id.base_title_bar_title)).setText(R.string.activity_detail);
		 }
		 
		 View vcancel = window.findViewById(R.id.cancel_comments_back_original);
		 vcancel.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					dlg.dismiss();
				}
		 });
		 
		 window.findViewById(R.id.show_comments_back_original).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				mInfoClicked = true;
				dlg.dismiss();
				if(string == R.string.add_event_txt) {
					//必填资料需填写
		  			if (!PrefHelper.getBoolean(ActivitysDetailActivity.this, "isfulluserinfo", false)) {
		  				showDialog(DIALOG_ADD_EVENT_NEED_FULL);
					} else {
						//资料都全，参加活动
						addEvent();
					}
				}
			}
		});
	}
	
	@Override
	public void onPostExecute(int what, Object o) {
		super.onPostExecute(what, o);
		Map<String, Object> objMap = (Map<String, Object>) o;
		switch (what) {
		case DataAsyncTask.TASK_ACTIVITYS_DETAIL:
			mObjMap = objMap;
			if(objMap==null){
				Tips("网络无连通，请稍后重试");
				this.finish();
				return;
			}
			initData(objMap);
			//将参加活动置为可见，否则会出问题
			findViewById(R.id.play).setVisibility(View.VISIBLE);
			break;
			
		case DataAsyncTask.TASK_ADD_EVENT:
			addEventPorcess(objMap);
			break;
			
		case DataAsyncTask.TASK_QUIT_EVENT:
			quitEventProcess(objMap);
			break;
		
		default:
			break;
		}
	}
	
	private void quitEventProcess(Map<String, Object> objMap) {
		if (!"0".equals(ModelUtils.getStringValue(objMap, "code"))) {
			mErrorMsg = ModelUtils.getStringValue(objMap, "errorMsg");
			showDialog(DIALOG_ADD_EVENT_ERROR);
		} else {
			//弹出信息
			mErrorMsg = "退出成功";
			ModelUtils.getMapValue(mObjMap, ActivityDetailInfoModel.PARAM_EVENT).put(RankingListModel.PARAM_STATUS, "0");
			removeDialog(DIALOG_ADD_EVENT_ERROR);
			showDialog(DIALOG_ADD_EVENT_ERROR);
		}
	}
	
	@Override
	protected void onPrepareDialog(int id, Dialog dialog) {
		switch (id) {
		case DIALOG_ADD_EVENT_ERROR:
			
			break;

		default:
			break;
		}
		super.onPrepareDialog(id, dialog);
	}

	@Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
        
            case DIALOG_ADD_EVENT: {
                AlertDialog.Builder builder = new Builder(this);
                builder.setPositiveButton(R.string.add_event_ok, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface paramDialogInterface, int paramInt) {
                    	Intent intent = new Intent(ActivitysDetailActivity.this, LoginActivity.class);
                    	ActivitysDetailActivity.this.startActivity(intent);
                    }
                }).
                setNegativeButton(R.string.add_event_cancel, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface paramDialogInterface, int paramInt) {
                    	
                    }
                }).setMessage(R.string.add_event_msg);
                return builder.create();
            }
            
            case DIALOG_ADD_EVENT_ERROR: {
            	AlertDialog.Builder builder = new Builder(this);
            	builder.setCancelable(true);
            	builder.setNegativeButton(R.string.add_event_ok, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface paramDialogInterface, int paramInt) {
                    	initData(mObjMap);
                    }
            	});
            	builder.setMessage(mErrorMsg);
            	return builder.create();
            }
            	
            case DIALOG_ADD_EVENT_NO_LOGIN: {
            	AlertDialog.Builder builder = new Builder(this);
            	builder.setMessage(R.string.login_please);
            	builder.setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						Intent intent= new Intent(ActivitysDetailActivity.this, LoginActivity.class);
						ActivitysDetailActivity.this.startActivity(intent);
					}
            	});
            	return builder.create();
            }
            
            case DIALOG_ADD_EVENT_NEED_FULL:{
            	AlertDialog.Builder builder = new Builder(this);
            	builder.setMessage(R.string.add_event_msg);
            	builder.setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						Intent intent= new Intent(ActivitysDetailActivity.this, UserInfoDetailActivity.class);
						ActivitysDetailActivity.this.startActivity(intent);
					}
            	});
            	return builder.create();
            }
        }
        return super.onCreateDialog(id);
    }
	

	
	

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_back:
			ActivitysDetailActivity.this.finish();
			break;
			
		case R.id.review:
			
			break;
			
		case R.id.activity_tip:
			showAddInfoDialog(R.string.add_detail_msg);
			break;
			
		case R.id.activity_detail:
			int visiable = mContentLayout.getVisibility();
			findViewById(R.id.arrowdown).setVisibility(visiable == View.VISIBLE ? View.VISIBLE:View.GONE);
			findViewById(R.id.arrowup).setVisibility(visiable == View.VISIBLE ? View.GONE : View.VISIBLE);
			mContentLayout.setVisibility(visiable == View.VISIBLE ? View.GONE : View.VISIBLE);
			mListView.setVisibility(visiable == View.VISIBLE ? View.VISIBLE :View.GONE);
			break;

		default:
			break;
		}
	}
}
